﻿using System;
using System.Linq;
using System.Web.Mvc;
using BLL;
using Model;
using Web.Helper;

namespace Web.Areas.Manager.Controllers
{

    [UserAuthorize]
    public class Sys_OrganizationController : Controller
    {

        //单个企业使用
        Sys_Users_BLL _Sys_Users_BLL = new Sys_Users_BLL();
        Sys_Organizations_BLL _Sys_Organizations_BLL = new Sys_Organizations_BLL();
        Sys_Enterprise_BLL _Sys_Enterprise_BLL = new Sys_Enterprise_BLL();

        public virtual ActionResult Index(int? pageIndex, string keyword)
        {
            var model = _Sys_Organizations_BLL.Get();

            if (!string.IsNullOrEmpty(keyword))
            {
                model = model.Where(a => a.Sys_Enterprise.EnterpriseName.Contains(keyword) || a.Department.Contains(keyword) || a.DepartmentCode.Contains(keyword));
            }

            //筛选 和该用户同一企业的信息
            model = model.Where(a => a.Sys_Enterprise.Sys_Users.Any(b => b.Id.Equals(new Guid(User.Identity.Name))));

            return View(model.ToPagedList(pageIndex));
        }


        public virtual ActionResult Details(Guid Id)
        {
            ViewBag.Sys_Enterprise = _Sys_Enterprise_BLL.Get();
            var item = _Sys_Organizations_BLL.Get(Id);
            return View(item);
        }

        public virtual ActionResult Edit(Guid? Id)
        {
            ViewBag.Sys_Enterprise = _Sys_Enterprise_BLL.Get();

            var item = _Sys_Organizations_BLL.Get(Id);
            return View(item);
        }

        [HttpPost]
        public virtual ActionResult Edit(Guid? Id, Sys_Organizations collection)
        {
            //企业ID设定为当前用户
            var user = _Sys_Users_BLL.Get(User.Identity.Name);

            collection.EnterpriseId = user.EnterpriseId;

            if (!ModelState.IsValid)
            {
                ViewBag.Sys_Enterprise = _Sys_Enterprise_BLL.Get();
                return View(collection);
            }
            _Sys_Organizations_BLL.Save(Id, ref collection);
            return RedirectToAction("Index", MyrouteValues.Get());
        }

        [HttpDelete]
        public virtual ActionResult Delete(Guid Id)
        {
            _Sys_Organizations_BLL.DeleteObject(Id);

            return RedirectToAction("Index", MyrouteValues.Get());
        }

    }
}
